﻿using B.MESUI.Login.EquipmentManagement.DeviceLedgerService;
using B.MESUI.Login.EquipmentManagement.DTO;
using B.MESUI.Login.EquipmentManagement.Model;
using B.MESUI.Login.WareHouseManage.Dtos;
using DevExpress.XtraEditors;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace B.MESUI.Login.WareHouseManage.IOWareHouse
{
    public partial class IOWareHouseForm : DevExpress.XtraEditors.XtraForm
    {
        private readonly DeviceGridPanel devicePanel;
        public IOWareHouseForm()
        {
            InitializeComponent();
            // 1. 创建控件实例
            devicePanel = new DeviceGridPanel();
            devicePanel.Dock = DockStyle.Fill;

            // 2. 加入到主窗体的某个Panel或直接加到this.Controls
            this.Controls.Add(devicePanel);

            // 3. 生成动态查询控件（如果没有查询就可以直接隐藏了）
            GenerateDeviceSearchControls();

            // 4. 绑定事件
            devicePanel.AddClicked += (s, e) => { /* 新增逻辑 */
                CreateIOWareHouseForm createIOWareHouseForm = new CreateIOWareHouseForm();
                createIOWareHouseForm.SaveCompleted += () =>
                {
                    FlushData();
                };
                createIOWareHouseForm.ShowDialog();
            };
            devicePanel.ExportClicked += (s, e) => { /* 导出逻辑 */ };
            devicePanel.DeleteClicked += async (s, e) =>
            {
                /* 删除逻辑 */
                var ids = devicePanel.GetSelectedIdsString();

                if (ids.Length == 0) { MessageBox.Show("请选择要删除的数据！！！"); }
                else
                {
                    //确认删除
                            if (MessageBox.Show("确定要删除选中的信息吗？", "提示", MessageBoxButtons.YesNo) != DialogResult.Yes)
                        return;

                    foreach (var rowHandle in ids.Split(','))
                    {
                        //var rowData = gridView1.GetRow(rowHandle) as LocationModel;
                        //if (rowData != null)
                        {
                            // 假设后端API为 DELETE http://localhost:5031/api/WareHouseDefinition/Delete/{id}
                            string apiUrl = $"http://39.103.49.30:9981/api/IOWareHouse/DeleteIOWAREHOUSERECORDMODEL?id={rowHandle}";
                            using (HttpClient client = new HttpClient())
                            {
                                var emptyContent = new StringContent("", Encoding.UTF8, "application/json");
                                var response = await client.PostAsync(apiUrl, emptyContent);
                                if (!response.IsSuccessStatusCode)
                                {
                                    MessageBox.Show($"删除ID为{rowHandle}的数据失败！");
                                }
                            }
                        }
                    }
                    //删除后刷新FlushData();
                    FlushData();
                    //使用httpclint调用自己的后端批量删除
                    //删除后刷新FlushData();
                }
            };
            //编辑事件
            devicePanel.EditClicked += (s, e) => { MessageBox.Show("你点击的ID是：" + e); };

            // 查询事件
            devicePanel.SearchClicked += async (s, e) =>
            {
                // 获取查询条件
                var searchConditions = devicePanel.GetSearchConditions();
                // 重置到第一页进行查询
                var result = await GetDeviceTypeListAsync(1, devicePanel.PageSize, searchConditions);
                BindDataSetColumns(result.Data);
                devicePanel.SetPageInfo(1, devicePanel.PageSize, result.TotalCount);
            };
            // 重置事件
            devicePanel.ResetClicked += async (s, e) =>
            {
                // 重置查询条件
                devicePanel.ResetSearchConditions();
                // 重新加载第一页数据
                var result = await GetDeviceTypeListAsync(1, devicePanel.PageSize);
                BindDataSetColumns(result.Data);
                devicePanel.SetPageInfo(1, devicePanel.PageSize, result.TotalCount);
            };

            // 5. 分页事件
            devicePanel.OnPageChanged += async (pageIndex, pageSize) =>
            {
                // 获取当前查询条件
                var searchConditions = devicePanel.GetSearchConditions();
                // 这里调用你的后端API
                var result = await GetDeviceTypeListAsync(pageIndex, pageSize, searchConditions); // 你的API
                BindDataSetColumns(result.Data);
                devicePanel.SetPageInfo(pageIndex, pageSize, result.TotalCount);
            };
            //// 1. 创建控件实例
            //devicePanel = new DeviceGridPanel();
            //devicePanel.Dock = DockStyle.Fill;

            //// 2. 加入到主窗体的某个Panel或直接加到this.Controls
            //this.Controls.Add(devicePanel);

            //// 3. 生成动态查询控件（如果没有查询就可以直接隐藏了）
            //GenerateDeviceSearchControls();

            //// 4. 绑定事件
            //devicePanel.AddClicked += (s, e) => { /* 新增逻辑 */
            //    CreateIOWareHouseForm createIO = new CreateIOWareHouseForm();

            //    createIO.SaveCompleted += () =>
            //    {
            //        FlushData();
            //    };

            //    createIO.ShowDialog();

            //};
            //devicePanel.ExportClicked += (s, e) => { /* 导出逻辑 */ };
            //devicePanel.DeleteClicked += async (s, e) =>
            //{
            //    /* 删除逻辑 */
            //    var ids = devicePanel.GetSelectedIdsString();

            //    if (ids.Length == 0) { MessageBox.Show("请选择要删除的数据！！！"); }
            //    else
            //    {
            //        // 确认删除
            //        if (MessageBox.Show("确定要删除选中的信息吗？", "提示", MessageBoxButtons.YesNo) != DialogResult.Yes)
            //            return;

            //        foreach (var rowHandle in ids.Split(','))
            //        {
            //            //var rowData = gridView1.GetRow(rowHandle) as LocationModel;
            //            //if (rowData != null)
            //            {
            //                // 假设后端API为 DELETE http://localhost:5031/api/WareHouseDefinition/Delete/{id}
            //                string apiUrl = $"http://localhost:5031/api/IOWareHouse/DeleteIOWAREHOUSERECORDMODEL?id={rowHandle}";
            //                using (HttpClient client = new HttpClient())
            //                {
            //                    var emptyContent = new StringContent("", Encoding.UTF8, "application/json");
            //                    var response = await client.PostAsync(apiUrl, emptyContent);
            //                    if (!response.IsSuccessStatusCode)
            //                    {
            //                        MessageBox.Show($"删除ID为{rowHandle}的数据失败！");
            //                    }
            //                }
            //            }
            //        }
            //        //删除后刷新FlushData();
            //        FlushData();
            //    }
            //};
            //devicePanel.EditClicked += (s, e) => { MessageBox.Show("你点击的ID是：" + e); };

            //// 查询事件
            //devicePanel.SearchClicked += async (s, e) =>
            //{
            //    // 获取查询条件
            //    var searchConditions = devicePanel.GetSearchConditions();
            //    // 重置到第一页进行查询
            //    var result = await GetDeviceTypeListAsync(1, devicePanel.PageSize, searchConditions);
            //    BindDataSetColumns(result.Data);
            //    devicePanel.SetPageInfo(1, devicePanel.PageSize, result.TotalCount);
            //};
            //// 重置事件
            //devicePanel.ResetClicked += async (s, e) =>
            //{
            //    // 重置查询条件
            //    devicePanel.ResetSearchConditions();
            //    // 重新加载第一页数据
            //    var result = await GetDeviceTypeListAsync(1, devicePanel.PageSize);
            //    BindDataSetColumns(result.Data);
            //    devicePanel.SetPageInfo(1, devicePanel.PageSize, result.TotalCount);
            //};

            //// 5. 分页事件
            //devicePanel.OnPageChanged += async (pageIndex, pageSize) =>
            //{
            //    // 获取当前查询条件
            //    var searchConditions = devicePanel.GetSearchConditions();
            //    // 这里调用你的后端API
            //    var result = await GetDeviceTypeListAsync(pageIndex, pageSize, searchConditions); // 你的API
            //    BindDataSetColumns(result.Data);
            //    devicePanel.SetPageInfo(pageIndex, pageSize, result.TotalCount);
            //};

        }
        ////添加查询控件方法
        //private void GenerateDeviceSearchControls()
        //{
        //    // 字段名和控件类型的映射（后端定义）
        //    var fieldMappings = new Dictionary<string, SearchControlType>
        //    {
        //        /*支持的控件类型：
        //       - SearchControlType.TextBox: 文本框
        //       - SearchControlType.ComboBox: 下拉框
        //       - SearchControlType.DateEdit: 日期选择器
        //       - SearchControlType.CheckBox: 复选框*/
        //        //示例前面查询的字段名，后面是控件类型：{ "Name", SearchControlType.TextBox },
        //        //{ "AssetNumber", SearchControlType.TextBox },
        //        //{ "Code", SearchControlType.TextBox },
        //        //{ "Name", SearchControlType.TextBox },
        //        //{ "State", SearchControlType.ComboBox }
        //    };

        //    // 显示名称映射（可选）
        //    var displayNames = new Dictionary<string, string>
        //    {
        //        //也就是修改查询显示的名称{ "Name", "设备名称" },
        //        //{ "AssetNumber", "设备序列号" },
        //        //{ "Code","编码" },
        //        //{ "Name", "名称" },
        //        //{ "State", "状态" }
        //    };

        //    // 下拉框选项（可选）
        //    var comboOptions = new Dictionary<string, List<string>>
        //    {
        //        //你的下拉里面的内容，左侧选择一个你添加的下拉名，手动就直接写，动态的就直接直接抓取给值就行了{ "State",     new     List<string> { "正常", "维修中", "报废", "闲置" } }
        //        //{ "State", new List<string> { "正常", "维修中", "报废", "闲置" } }
        //    };
        //    //调用动态生成查询控件方法
        //    devicePanel.GenerateSearchControls(fieldMappings, displayNames, comboOptions);
        //}
        ///// <summary>
        ///// 绑定数据、隐藏指定列、设置列名方法
        ///// </summary>
        //private void BindDataSetColumns(List<IOWareHouseModel> data)
        //{
        //    // 需要隐藏的列名
        //    var hideColumnNames = new[] { "IsDeleted", "AnotherColumn" };

        //    // 列名映射
        //    var columnCaptions = new Dictionary<string, string>
        //    {
        //        { "id", "唯一编号" },
        //        { "createtime", "添加时间" },
        //        { "updatetime", "修改时间" },
        //        { "ordernumber", "单号编码" },
        //        { "barcode", "条码" },
        //        { "documenttype", "设备名称" },
        //        { "num", "数量" } ,
        //        { "operateusername", "操作人" } ,
        //        { "operatetime", "操作时间" }
        //        // 其他字段...
        //    };

        //    devicePanel.SetDataSource(data);
        //    devicePanel.gridView.PopulateColumns();

        //    foreach (var colName in hideColumnNames)
        //    {
        //        var col = devicePanel.gridView.Columns[colName];
        //        if (col != null)
        //            col.Visible = false;
        //    }
        //    devicePanel.SetColumnCaptions(columnCaptions);
        //}
        ////4. }
        //// 获取显示值方法，实际根据你的后端API来写
        //private async Task<(List<IOWareHouseModel> Data, int TotalCount)> GetDeviceTypeListAsync(int pageIndex, int pageSize, Dictionary<string, object> searchConditions = null)
        //{
        //    // 调用后端接口，返回数据和总数
        //    using (var client = new HttpClient())
        //    {
        //        // 构建查询参数
        //        var queryParams = new List<string>
        //        {
        //            $"PageIndex={pageIndex}",
        //            $"PageSize={pageSize}"
        //        };

        //        // 添加查询条件
        //        if (searchConditions != null && searchConditions.Count > 0)
        //        {
        //            foreach (var condition in searchConditions)
        //            {
        //                if (condition.Value != null)
        //                {
        //                    string value = condition.Value.ToString();
        //                    if (!string.IsNullOrEmpty(value))
        //                    {
        //                        // 根据值类型进行不同的处理
        //                        if (condition.Value is DateTime dateTime)
        //                        {
        //                            value = dateTime.ToString("yyyy-MM-dd");
        //                        }
        //                        else if (condition.Value is bool boolValue)
        //                        {
        //                            value = boolValue.ToString().ToLower();
        //                        }

        //                        queryParams.Add($"{condition.Key}={Uri.EscapeDataString(value)}");
        //                    }
        //                }
        //            }
        //        }

        //        string queryString = string.Join("&", queryParams);
        //        //改成自己的接口
        //        string url = $"http://localhost:5031/api/IOWareHouse/GetIOWAREHOUSERECORDMODEL?{queryString}";
        //        //替换为自己的传值方式"Get","Post","Put","Delete"
        //        var response = await client.GetAsync(url);
        //        response.EnsureSuccessStatusCode();
        //        var json = await response.Content.ReadAsStringAsync();
        //        //替换为你自己的数据模型
        //        var result = JsonConvert.DeserializeObject<ApiPaging<IOWareHouseModel>>(json);
        //        return (result.PageDatas, result.TotalCount);
        //    }
        //}
        ///// <summary>
        ///// 刷新数据
        ///// </summary>
        //private async void FlushData()
        //{
        //    // 首次加载第一页
        //    var result = await GetDeviceTypeListAsync(1, 20);//默认1页20条
        //    BindDataSetColumns(result.Data);
        //    devicePanel.SetPageInfo(1, 20, result.TotalCount);
        //}

        private void IOWareHouseForm_Load(object sender, EventArgs e)
        {
            FlushData();
        }
        //添加查询控件方法
        private void GenerateDeviceSearchControls()
        {
            // 字段名和控件类型的映射（后端定义）
            var fieldMappings = new Dictionary<string, SearchControlType>
            {
                /*支持的控件类型：
               - SearchControlType.TextBox: 文本框
               - SearchControlType.ComboBox: 下拉框
               - SearchControlType.DateEdit: 日期选择器
               - SearchControlType.CheckBox: 复选框*/
                //示例前面查询的字段名，后面是控件类型：{ "Name", SearchControlType.TextBox },

            };

            // 显示名称映射（可选）
            var displayNames = new Dictionary<string, string>
            {
                //也就是修改查询显示的名称{ "Name", "设备名称" },

            };

            // 下拉框选项（可选）
            var comboOptions = new Dictionary<string, List<string>>
            {
                //你的下拉里面的内容，左侧选择一个你添加的下拉名，手动就直接写，动态的就直接直接抓取给值就行了{ "State", new List<string> { "正常", "维修中", "报废", "闲置" } }
            };
            //调用动态生成查询控件方法
            devicePanel.GenerateSearchControls(fieldMappings, displayNames, comboOptions);
        }
        /// <summary>
        /// 绑定数据、隐藏指定列、设置列名方法
        /// </summary>
        private void BindDataSetColumns(List<IOWareHouseModel> data)
        {
            // 需要隐藏的列名
            var hideColumnNames = new[] { "IsDeleted", "AnotherColumn","Id" };

            // 列名映射
            var columnCaptions = new Dictionary<string, string>
            {
                //{ "Id", "设备编号" },
                { "id", "唯一编号" },
                { "createtime", "添加时间" },
                { "updatetime", "修改时间" },
                { "ordernumber", "单号编码" },
                { "barcode", "条码" },
                { "documenttype", "设备名称" },
                { "num", "数量" } ,
                { "operateusername", "操作人" } ,
                { "operatetime", "操作时间" }
                // 其他字段...
            };

            devicePanel.SetDataSource(data);
            foreach (var colName in hideColumnNames)
            {
                var col = devicePanel.gridView.Columns[colName];
                if (col != null)
                    col.Visible = false;
            }
            devicePanel.SetColumnCaptions(columnCaptions);
        }
        // 获取显示值方法，实际根据你的后端API来写
        private async Task<(List<IOWareHouseModel> Data, int TotalCount)> GetDeviceTypeListAsync(int pageIndex, int pageSize, Dictionary<string, object> searchConditions = null)
        {
            // 调用后端接口，返回数据和总数
            using (var client = new HttpClient())
            {
                // 构建查询参数
                var queryParams = new List<string>
        {
            $"PageIndex={pageIndex}",
            $"PageSize={pageSize}"
        };

                // 添加查询条件
                if (searchConditions != null && searchConditions.Count > 0)
                {
                    foreach (var condition in searchConditions)
                    {
                        if (condition.Value != null)
                        {
                            string value = condition.Value.ToString();
                            if (!string.IsNullOrEmpty(value))
                            {
                                // 根据值类型进行不同的处理
                                if (condition.Value is DateTime dateTime)
                                {
                                    value = dateTime.ToString("yyyy-MM-dd");
                                }
                                else if (condition.Value is bool boolValue)
                                {
                                    value = boolValue.ToString().ToLower();
                                }

                                queryParams.Add($"{condition.Key}={Uri.EscapeDataString(value)}");
                            }
                        }
                    }
                }

                string queryString = string.Join("&", queryParams);
                //改成自己的接口
                string url = $"http://39.103.49.30:9981/api/IOWareHouse/GetIOWAREHOUSERECORDMODEL?{queryString}";
                //替换为自己的传值方式"Get","Post","Put","Delete"
                var response = await client.GetAsync(url);
                response.EnsureSuccessStatusCode();
                var json = await response.Content.ReadAsStringAsync();
                //替换为你自己的数据模型
                var result = JsonConvert.DeserializeObject<ApiPaging<IOWareHouseModel>>(json);
                foreach (var item in result.PageDatas)
                {
                    item.Id = item.id;
                }
                return (result.PageDatas, result.TotalCount);
            }
        }
        /// <summary>
        /// 刷新数据
        /// </summary>
        private async void FlushData()
        {
            // 首次加载第一页
            var result = await GetDeviceTypeListAsync(1, 20);//默认1页20条
            BindDataSetColumns(result.Data);
            devicePanel.SetPageInfo(1, 20, result.TotalCount);
        }
    }
}